package com.lu.sb210207.config;

import com.lu.sb210207.quartz.MyJobFactory;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

/**
 * 创建配置类
 */
@Configuration
public class QuartzConfiguration {

    @Autowired
    private MyJobFactory myJobFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean sc=new SchedulerFactoryBean();
        try {
            //加载自定义的quartz.properties文件
            sc.setQuartzProperties(quartzProperties());
            //设置自定义的JobFactory工程类，解决Spring不能再Quartz框架中Bean的注入问题
            sc.setJobFactory(myJobFactory);
            return sc;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //指定quartz.properties
    @Bean
    public Properties quartzProperties() throws IOException {
        //创建Properties属性工厂Bean类
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        //加载自定义的quartz.properties
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }


    //创建schedule
    @Bean(name = "scheduler")
    public Scheduler scheduler() {
        //从调度器工厂Bean中获取调取度实例对象
        return schedulerFactoryBean().getScheduler();
    }
}
